using System;
using System.Collections.Generic;
using System.Text;

namespace LoanPrequalificationSystem.Model.Borrowers
{
    public class BorrowerService
    {
        private IBorrowerRepository borrowerRepository;

        public BorrowerService(IBorrowerRepository borrowerRepository)
        {
            this.borrowerRepository = borrowerRepository;
        }

        public Borrower FindBorrowerById(Guid BorrowerId)
        {
            var borrower = borrowerRepository.FindBy(BorrowerId);

            if (borrower == null)
                throw new Exception(string.Format("Can't find a borrower by Id '{0}'", BorrowerId).ToString());

            return borrower;
        }

        public void Save(Borrower borrower)
        {
            if (borrower.GetBrokenRules().Count > 0)
                throw new ArgumentException(string.Format("This borrower can't be saved in its present state. '{0}'",
                                                          GetBrokenRulesToStringFor(borrower.GetBrokenRules())));

            borrowerRepository.Save(borrower);
        }
        public List<Borrower> FindAll()
        {
            return borrowerRepository.FindAll();
        }

        private string GetBrokenRulesToStringFor(List<BrokenBusinessRule> brokenRules)
        {
            var sbBrokenRules = new StringBuilder();

            foreach (var br in brokenRules)
            {
                sbBrokenRules.Append(br.Rule);
            }

            return sbBrokenRules.ToString();
        }
    }
}